﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using Argos.Data.Model;
using System.Workflow.ComponentModel;
using Argos.Windows.Forms;
using System.Windows.Forms;

namespace Argos.Design
{
	public sealed class TestActivityPropertiesTypeEditor : UITypeEditor
	{

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			Test t = context.Instance as Test;
			if (null != t)
			{
				if (null != t.ActivityType)
				{
					Activity activity = (Activity)Activator.CreateInstance(t.ActivityType);
					Dictionary<string, object> properties = new Dictionary<string, object>();
					Reflector.GetObjectProperties(activity, properties, Predicates.BindableBrowsableActivityPropertyMatcher);
					if (properties.Count == 0)
					{
						throw new InvalidOperationException(string.Format("There are no editable properties on '{0}'.", t.ActivityType));
					}

					Reflector.SetObjectProperties(activity, t.ActivityProperties);

					using (PropertyEditorDialog dlg = new PropertyEditorDialog(activity))
					{
						if (dlg.ShowDialog() == DialogResult.OK)
						{
							properties = new Dictionary<string, object>();
							Reflector.GetObjectProperties(activity, properties, Predicates.BindableBrowsableActivityPropertyMatcher);
							return properties;
						}
					}
				}
				else
				{
					throw new InvalidOperationException("Cannot edit activity properties because the activity has not been set.");
				}
			}

			return value;
		}

		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			return UITypeEditorEditStyle.Modal;
		}

	}
}
